/*
 * @Description: 
 * @Author: 张民鸿
 * @Date: 2021-10-11 11:13:17
 * @FilePath: /cloud-register-business/Users/zhang/Desktop/zhang/Cloud-Registration-Desk/src/components/VerificationCodeInput/index.tsx
 * @LastEditTime: 2021-10-22 11:12:52
 * @LastEditors: MelodyJerry
 */
import React, { useState, useEffect, useRef } from 'react';
import { Input, Button, message } from 'antd';
import { connect, useDispatch } from 'react-redux';
import { SAVE_CODEURL } from '~reducers/common';
import { SizeType } from 'antd/lib/config-provider/SizeContext';
import { VerifiedOutlined } from '@ant-design/icons';
interface VerificationCodeInputProps {
    onChange?: React.ChangeEventHandler<HTMLInputElement> | undefined
    value?: string
    img?: string
    size: SizeType
    disabled?: boolean
    placeholder?: string
    getCodeOk: () => Promise<any>
}
const VerificationCodeInput = ({ onChange, value, img, size, disabled, placeholder, getCodeOk }: VerificationCodeInputProps): React.ReactElement => {
    const [codeVal, setCodeVal] = useState(value);
    const [count, setcount] = useState(60)
    const intervalRef = useRef<any>(null);
    function triggerChange(val: any) {
        onChange && onChange(val);
    }

    function changeHandle(e: React.ChangeEvent<HTMLInputElement>) {
        let val = e.target.value || "";
        val = val.trim();
        setCodeVal(val);
        triggerChange(val || undefined);
    }
    //发送验证码
    async function sendCode() {
        if (count == 60) {
            await getCodeOk()
            //发送验证码
            intervalRef.current = setInterval(() => {
                setcount(count => count - 1)
            }, 1000)

        }
    }
    useEffect(() => {
        return () => {
            setcount(60)
            clearInterval(intervalRef.current);
        };
    }, [])
    useEffect(() => {
        if (count == 0) {
            setcount(60)
            clearInterval(intervalRef.current)
        }
    }, [count])
    return (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Input
                value={codeVal}
                size={size}
                disabled={disabled}
                placeholder={placeholder}
                onChange={changeHandle}
                style={{ width: '60%' }}
                prefix={<VerifiedOutlined />}
            />
            <Button style={{ width: "100px" }} type="default" onClick={sendCode}>{count == 60 ? "获取验证码" : count}</Button>
        </div>
    )
}

export default connect((state: any) => ({ img: state.common.img, imgKey: state.common.imgKey }))(VerificationCodeInput)